import { Radio,  Space, TreeSelect, DatePicker,Select, Row } from 'antd';


import ECharts from 'echarts-for-react';
import styles from './style.less';
const { Option } = Select;
import React, { useState, useRef, useEffect } from 'react';
import ProTable, { ActionType } from '@ant-design/pro-table';
import { queryAreaTree } from '@/services/area';
import { queryDeviceTypeList } from '@/services/devicetype';
import moment from 'moment'
import { queryOperationAnalysis,totalDeviceState,totalRunStateByDevice,totalRunStateByState } from '@/services/deviceupdatestate';
import { formatSeconds } from '@/utils/utils';
const defalutTypenum = [
  { value: 5, name: '正常运行' },
  { value: 2, name: '报警' },
  { value: 1, name: '故障' },
  { value: 1, name: '未开机' }
];
const Survey: React.FC = () => {

  const actionRef = useRef<ActionType>();
  const [typeId, setTypeId] = useState<number>(1);
  const [typeName, setTypeName] = useState<String>('变频器');
  const [areaId, setAreaId] = useState<number>();
  const [typenum, setTypenum] = useState(defalutTypenum);
  const [totalnum, setTotalnum] = useState({});
  const [type, setType] = useState('date');

  const [dataSource, setDataSource] = useState([]);
  const [areaTreeData, setAreaTreeData] = useState<API.TreeNodeItem[]>([]);
  const [deviceTypeList, setDeviceTypeList] = useState<API.DeviceTypeItem[]>([]);
  const [cdate, setCdate] = useState(moment());
  useEffect(() => {
    queryAreaTree().then(function(trees){
      setAreaTreeData(trees);
    })
    queryDeviceTypeList().then(function(devices){
      setDeviceTypeList(devices);
    })
    
    
  }, []);

  useEffect(() => {
    queryOperationAnalysis({typeId,areaId}).then(function(list){
    
      setDataSource(list)
     
    })
    totalDeviceState({typeId,areaId}).then(function(data){
      setTotalnum(data)
      setTypenum(data.chartData);
    })

    totalRunStateByDevice({typeId,areaId}).then(function(data){
      let new_data = { ...option };
      new_data.series=data.seriesList;
      new_data.yAxis.data=data.deviceList;
      setChartData(new_data)
     
    })
    let date= moment(cdate).format("YYYY-MM-DD");

    totalRunStateByState({typeId,areaId,type,date}).then(function(data){
      let new_data = { ...option1 };
      new_data.series=data.seriesList;
      new_data.xAxis.data=data.timeList;
      setChartDataByState(new_data)
      
    })

   
    console.log(type)
   
  }, [typeId, areaId,cdate,type]);






  const columns = [
    {
      title: '设备名称',
     
      dataIndex: 'device',
    
      render: (text, record) => (
        <Space size="middle">
        {text.deviceName}
       </Space>
      
      ),
    },
    {
      title: '区域',
      dataIndex: 'device',
      render: (text, record) => (
        <Space size="middle">
        {text.areaName}
       </Space>
      
      ),
    },
    
  
   {
      title: '状态',
      dataIndex: 'state'
    },
    {
      title: '状态更新时间',
      dataIndex: 'updateTime',
    },
    {
      title: '状态持续时长',
      dataIndex: 'stateDuration',
    },
  ];

  const DEFAULT_OPTION = {
    color: ['#B0ADAD','#4FD97B', '#f4b766', '#333'],
    tooltip: {
      trigger: 'item',
    },
  
    legend: {
      show: false,
    },
    series: [
      {
       
        type: 'pie',
        radius: ['50%', '70%'],
        data: typenum,
      },
    ],
  };


  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        // Use axis to trigger tooltip
        type: 'shadow' // 'shadow' as default; can also be 'line' or 'shadow'
      }, formatter:function(params){
        var  tooltip=params[0].name;
        for(var i = 0; i < params.length; i++){
          console.log(params[i])
          tooltip+=' <br/> '+params[i].marker + params[i].seriesName + ': ' +   formatSeconds(params[i].value)
        }
        return tooltip;
        }
    },
    legend: {
      textStyle: {
        color: '#fff',
      },
    },
    grid: {
      left: '3%',
      // right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      axisLine: {
        lineStyle: {
          type: 'dashed',
          color: '#fff',
        },
      },
      splitLine: {
        show: false,
        lineStyle: {
          type: 'dashed',
        },
      },
      type: 'value',
      name: '时间:s'
    },
    yAxis: {
      axisLine: {
        lineStyle: {
          type: 'dashed',
          color: '#fff',
        },
      },
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed',
        },
      },
      type: 'category',
      data: []
    },
    series: []
  };
  

  var option1 = {
    legend: {
      textStyle: {
        color: '#fff',
      },
    },
  
    tooltip: {  trigger: 'axis',
    axisPointer: {
      // Use axis to trigger tooltip
      type: 'shadow' // 'shadow' as default; can also be 'line' or 'shadow'
    }, formatter:function(params){
      var  tooltip=params[0].name;
      for(var i = 0; i < params.length; i++){
        console.log(params[i])
        tooltip+=' <br/> '+params[i].marker + params[i].seriesName + ': ' +   formatSeconds(params[i].value)
      }
      return tooltip;
      }},

    xAxis: {
      axisLine: {
        lineStyle: {
          type: 'dashed',
          color: '#fff',
        },
      },
      splitLine: {
        show: false,
        lineStyle: {
          type: 'dashed',
        },
      },
      type: 'category',
      data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    },

    yAxis: {
      axisLine: {
        lineStyle: {
          type: 'dashed',
          color: '#fff',
        },
      },
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed',
        },
      },
      name: '时间:s'
    },
    series: [ {
      name: 'Email',
      type: 'line',
     
      data: [120, 132, 101, 134, 90, 230, 210]
    },
    {
      name: 'Union Ads',
      type: 'line',
     
      data: [220, 182, 191, 234, 290, 330, 310]
    },
    {
      name: 'Video Ads',
      type: 'line',
   
      data: [150, 232, 201, 154, 190, 330, 410]
    },
    {
      name: 'Direct',
      type: 'line',
     
      data: [320, 332, 301, 334, 390, 330, 320]
    }],
  };
  const [chartData, setChartData] = useState<Object>(option);

  const [chartDataByState, setChartDataByState] = useState<Object>(option1);

  function SwitchablePicker() {
     
    return (
      <Space>
        <div  className={styles.inputBg} >
          <Select value={type}  bordered={false}    dropdownStyle={{ background: 'rgb(20, 49, 115)'}}  onChange={setType}>
              <Option value="date">日</Option>
              {/* <Option value="week">周</Option> */}
              <Option value="month">月</Option>
              {/* <Option value="quarter">季度</Option> */}
              <Option value="year">年</Option>
          </Select>
        </div>
        <div  className={styles.inputBg} >
          <PickerWithType type={type} onChange={value =>{ setCdate(value)}} />
        </div>
      </Space>
    );
  }

  function PickerWithType({ type, onChange }) {
    if (type === 'date') return <DatePicker  value={cdate}  popupStyle={{ background: 'rgb(20, 49, 115)'}}   bordered={false}  onChange={onChange} />;
    return <DatePicker  value={cdate} popupStyle={{ background: 'rgb(20, 49, 115)'}}     bordered={false}  picker={type} onChange={onChange} />;
  }
  return (
    <div className={styles.main}>
      <Row style={{alignItems:'center',margin:'0 0 20px', justifyContent: 'space-between'}}>
         <div  className={styles.title}>{typeName}运行分析</div>
              <div className={styles.flex}>
         <div  className={styles.inputBg} >
            <Select  placeholder="请选择设备类型"  labelInValue defaultValue={{value:deviceTypeList[0]?.typeId||1,label:deviceTypeList[0]?.typeName||'变频器',key:deviceTypeList[0]?.typeId||1}}  onChange={(e)=>{

                setTypeId(e.value);
                setTypeName(e.label);
            }}>
               {deviceTypeList.map((item) => (
                <Option key={item.typeId} value={item.typeId}>
                  {item.typeName}
                </Option>
               ))}
              </Select>

              </div> 
            <div  className={styles.inputBg} style={{    margin: '0 8px'}} >
            <TreeSelect  allowClear onChange={(e)=> setAreaId(e)}
               style={{ width: '260px',marginLeft:'10px' }} dropdownStyle={{ maxHeight: 400, overflow: 'auto' }} treeData={areaTreeData} placeholder="请选择所在区域"  treeDefaultExpandAll />
            </div> 
            <SwitchablePicker />
          </div> 
       </Row>
      <view  className={styles.top}>
        <view  className={styles.itemBox} >
            <div  className={styles.item}  >
              <div className={styles.name}>设备总数</div>
              <div className={styles.num}>{totalnum?.allCount}</div>
            </div>
          </view>
          <view  className={styles.itemBox} >
            <div  className={ [styles.item, styles.runBg].join(' ') }  >
              <div className={styles.name}>运行数量</div>
              <div className={styles.num}>{totalnum?.runCount}</div>
            </div>
          </view>
          <view  className={styles.itemBox} >
            <div  className={[styles.item, styles.alarmBg].join(' ') }  >
              <div className={styles.name}>报警数量</div>
              <div className={styles.num}>{totalnum?.alarmCount}</div>
            </div>
          </view>
          <view  className={styles.itemBox} >
            <div  className={[styles.item, styles.faultBg].join(' ') }  >
              <div className={styles.name}>故障数量</div>
              <div className={styles.num}>{totalnum?.faultCount}</div>
            </div>
          </view>
          <view  className={styles.itemBox} >
            <div  className={[styles.item, styles.noOnBg].join(' ') }  >
              <div className={styles.name}>未开机数量</div>
              <div className={styles.num}>{totalnum?.noOnCount}</div>
            </div>
          </view>
      </view>
      <view className={styles.flex}>
        <div className={styles.modalItem}>
          <Row className={styles.sinTitle}>
            <span className={styles.signLine}></span>
            <span>运行占比</span>
          </Row>
          <ECharts option={DEFAULT_OPTION} style={{ width: '100%' }} />
        </div>
        <div className={styles.modalItem}>
          <Row className={styles.sinTitle}>
            <span className={styles.signLine}></span>
            <span>运行状态</span>
           </Row>
           <ProTable<API.DeviceItem> 
            headerTitle=""
            actionRef={actionRef}
            rowKey="deviceId"
            toolBarRender={false}
            search={false}
            dataSource={dataSource}
            columns={columns}
            pagination={false}
          />
        </div>
      </view>
      <view className={styles.flex}>
        <div className={styles.modalItem}>
          <Row className={styles.sinTitle}>
            <span className={styles.signLine}></span>
            <span>设备运行时间统计</span>
          </Row>
         
          <ECharts option={chartData} style={{ height: 360, width: '100%' }} />
          
        </div>
        <div className={styles.modalItem}>
         <Row className={styles.sinTitle}>
            <span className={styles.signLine}></span>
            <span>{typeName}设备运行趋势</span>
          </Row>
          
          <ECharts option={chartDataByState} style={{ height: 380, width: '100%' }} />
        </div>

      </view>
    </div>
  );
};

export default Survey;
